/**
 * 分页
 */
!function ($) {

    "use strict";

    /**
     * 默认参数
     */
    var defaults = {
        //每页显示记录数
        "pageSize": 10,
        //当前页号
        "pageNumber": 1,
        //总记录个数
        "totalRow": 0,
        //显示页码个数，建议使用奇数
        "pageBarSize": 5,
        //每页显示记录数设置
        "pageSizeMenu": [5, 10, 20, 50, 100],
        //业务参数集，参数为function，function的返回值必须为Object格式：{a:1,b:2,……}
        "params": undefined,
        //自定义样式
        "className": undefined,
        //异步处理分页
        "asyncLoad": false,
        //异步处理对象容器，支持使用jquery表达式
        //服务端返回页面模式使用
        "asyncTarget": 'body',
        //异步提交方式，默认POST
        "asyncType": 'POST',
        //是否使用服务端返回页面的形式
        //该参数仅在异步处理模式下有效（asyncLoad = true）
        "serverSidePage": false,
        //异步数据模式自定义处理回调，ajax请求服务端并返回json数据后，可使用数据进行自定义页面渲染
        "render": undefined,
        //分页跳转URL
        "url": '',
        //异步方式分页后，并在返回的页面内容嵌入到指定位置后，执行该回调，跳转方式不执行该回调
        //参数param，插件的参数集
        "callback": $.noop
    };

    /**
     * 模板
     */
    var template = '<ul class="m-datatable__pager-nav">' +
        '<li id="paginationFirstPage" class="paginationLi">' +
        '<a class="m-datatable__pager-link m-datatable__pager-link--first" href="javascript:">' +
        '<i class="la la-angle-double-left"></i>' +
        '</a>' +
        '</li>' +
        '<li class="paginationLi" style="display: none;">' +
        '<a class="m-datatable__pager-link m-datatable__pager-link--more-prev" href="javascript:">' +
        '<i class="la la-ellipsis-h"></i>' +
        '</a>' +
        '</li>' +
        '<li id="paginationPreviousPage" class="paginationLi">' +
        '<a class="m-datatable__pager-link m-datatable__pager-link--prev" href="javascript:">' +
        '<i class="la la-angle-left"></i>' +
        '</a>' +
        '</li>' +
        '<li id="paginationNextPage" class="paginationLi">' +
        '<a class="m-datatable__pager-link m-datatable__pager-link--next" href="javascript:">' +
        '<i class="la la-angle-right"></i>' +
        '</a>' +
        '</li>' +
        '<li id="paginationLastPage" class="paginationLi">' +
        '<a class="m-datatable__pager-link m-datatable__pager-link--last" href="javascript:">' +
        '<i class="la la-angle-double-right"></i>' +
        '</a>' +
        '</li>' +
        '</ul>' +
        '<div id="paginationCount" class="m-datatable__pager-info">' +
        '<span class="m-datatable__pager-detail"></span>' +
        '</div>';
    /**
     * 构造方法
     */
    var pagination = function (element, p) {
        this.$container = element;
        this.p = p;
        this.pageNumber = Number(p.pageNumber);
        this.pageSize = Number(p.pageSize);
        this.totalRow = Number(p.totalRow);
    };
    /**
     * 插件常量
     */
    pagination.version = '1.0';
    /**
     * 绑定事件的名称，使用了 pagination 的命名空间
     */
    pagination.eventName = 'click.pagination';
    /**
     * 初始化分页
     */
    pagination.prototype.init = function () {
        if (this.pageSize >= this.totalRow) {
            return;
        }
        if ((this.totalRow / this.pageSize + 1) < this.pageNumber) {
            return;
        }
        var p = this.p, elem = this.$container;
        $(elem).append(template);
        if (p.className) $('ul', elem).addClass(p.className);

        if (!p.asyncLoad) this.populate();

        if (p.asyncLoad) this.pageSwitch(1);
    };
    /**
     * 更新分页信息
     */
    pagination.prototype.updatePageInfo = function () {
        if ($.type(this.pageNumber) === 'undefined' || $.type(this.pageNumber) !== 'number' || this.pageNumber <= 0)
            this.pageNumber = defaults.pageNumber;
        if ($.type(this.pageSize) === 'undefined' || $.type(this.pageSize) !== 'number' || this.pageSize <= 0)
            this.pageSize = defaults.pageSize;
        if ($.type(this.totalRow) !== 'undefined' && $.type(this.totalRow) === 'number')
            this.totalPage = Math.ceil(this.totalRow / this.pageSize);
    };
    /**
     * 数据填充
     */
    pagination.prototype.populate = function () {
        this.updatePageInfo();
        var elem = this.$container, p = this.p, pNum = this.pageNumber;
        var _class, _start, _end, _half = Math.floor(p.pageBarSize / 2);

        //总页数小于显示页码个数
        if (this.totalPage < p.pageBarSize) {
            _start = 1;
            _end = this.totalPage;
            //当前页码小于显示页码个数的一半
        } else if (pNum <= _half) {
            _start = 1;
            _end = p.pageBarSize;
            //当前页码大于等于总页数减去显示页码个数一半的值
        } else if (pNum >= (this.totalPage - _half)) {
            _start = this.totalPage - p.pageBarSize + 1;
            _end = this.totalPage;
            //常规情况
        } else {
            _start = pNum - _half;
            _end = _start + p.pageBarSize - 1;
        }

        //移除分页控制按钮除外的所有页码
        $('li:not(.paginationLi)', $(elem)).remove();

        // 文字说明
        $('#paginationCount span').text(AlertMessage.getMessageAlertPaginationPageSize() + ' ' + this.pageSize
            + ' ' + AlertMessage.getMessageAlertPaginationTotalRow() + ' ' + this.totalRow + ' '
            + AlertMessage.getMessageAlertPaginationCount());

        //$('#paginationCount span').text('显示 ' + this.pageSize + ' / ' + this.totalRow + ' 条数据');

        // 设置页码及事件
        for (var i = _start; i <= _end; i++) {
            _class = (i === pNum) ? 'class="m-datatable__pager-link m-datatable__pager-link-number m-datatable__pager-link--active"' : 'class="m-datatable__pager-link m-datatable__pager-link-number"';
            var curPage = $('<li><a ' + _class + ' href="javascript:">' + i + '</a></li>').insertBefore($('#paginationNextPage', $(elem)), $(elem));
            if (i !== pNum) this.setFunction($(curPage), i);
        }

        // 处理静态控制按钮样式及链接
        var _fNum, _pNum, _nNum, _lNum;
        if (pNum === 1) {
            $('#paginationFirstPage a,#paginationPreviousPage a', $(elem)).addClass('m-datatable__pager-link--disabled');
            _fNum = -1;
            _pNum = -1;
        } else {
            $('#paginationFirstPage a,#paginationPreviousPage a', $(elem)).removeClass('m-datatable__pager-link--disabled');
            _fNum = 1;
            _pNum = pNum > 1 ? pNum - 1 : 1;
            // 上一页省略号
            if (_start > 1) {
                $('<li class="paginationLi"><a class="m-datatable__pager-link m-datatable__pager-link--more-prev" href="javascript:"><i class="la la-ellipsis-h"></i></a></li>').insertAfter($('#paginationPreviousPage', $(elem)));
                var paginationSpan = $('<li class="paginationLi"><a class="m-datatable__pager-link m-datatable__pager-link-number" href="javascript:">' + _fNum + '</a></li>').insertAfter($('#paginationPreviousPage', $(elem)));
                this.setFunction($(paginationSpan), _fNum);
            }
        }
        this.setFunction($('#paginationFirstPage a', $(elem)), _fNum);
        this.setFunction($('#paginationPreviousPage a', $(elem)), _pNum);

        if (pNum === this.totalPage || this.totalPage === 0) {
            $('#paginationNextPage a,#paginationLastPage a', $(elem)).addClass('m-datatable__pager-link--disabled');
            _nNum = -1;
            _lNum = -1;
        } else {
            $('#paginationNextPage a,#paginationLastPage a', $(elem)).removeClass('m-datatable__pager-link--disabled');
            _nNum = pNum < this.totalPage ? pNum + 1 : this.totalPage;
            _lNum = this.totalPage;

            // 下一页 省略号
            if (this.totalPage > _end) {
                $('<li class="paginationLi"><a class="m-datatable__pager-link m-datatable__pager-link--more-next" href="javascript:"><i class="la la-ellipsis-h"></i></a></li>').insertBefore($('#paginationNextPage', $(elem)), $(elem));
                var paginationSpan = $('<li class="paginationLi"><a class="m-datatable__pager-link m-datatable__pager-link-number" href="javascript:">' + _lNum + '</a></li>').insertBefore($('#paginationNextPage', $(elem)), $(elem));
                this.setFunction($(paginationSpan), _lNum);
            }
        }

        this.setFunction($('#paginationNextPage a', $(elem)), _nNum);
        this.setFunction($('#paginationLastPage a', $(elem)), _lNum);
    };

    /**
     * 获得业务参数的URL字符串（URL跳转方式使用）
     */
    pagination.prototype.buildParamsStr = function () {
        var str = '', p = this.p;
        if (p.params && $.isFunction(p.params)) {
            var pa = p.params(), attr;
            if ($.isPlainObject(pa)) {
                for (attr in pa) {
                    str += '&' + attr + '=' + pa[attr];
                }
            }
        }
        return str;
    };
    /**
     * 设置服务端请求参数对象（异步使用ajax请求时执行）
     */
    pagination.prototype.getParams = function (pageNumber) {
        var param = {}, p = this.p;
        param.pageNumber = pageNumber;
        param.pageSize = this.pageSize;
        if (p.params && $.isFunction(p.params)) {
            var pa = p.params();
            if ($.isPlainObject(pa) && !$.isEmptyObject(pa)) param = $.extend({}, param, pa);
        }
        return param;
    };
    /**
     * 设置事件
     */
    pagination.prototype.setFunction = function (obj, pageNumber) {
        var self = this;
        $(obj).off(pagination.eventName).on(pagination.eventName, function () {
            self.pageSwitch(pageNumber);
        });
    };

    /**
     * 设置页面点击事件处理
     * event：事件对象
     * 若pageNumber参数为-1，而设置当前页不处理操作
     */
    pagination.prototype.pageSwitch = function (pageNumber) {
        var self = this, p = this.p;
        if (pageNumber === undefined && typeof(pageNumber) !== 'number') pageNumber = self.pageNumber;
        if (pageNumber === -1) return;
        if (pageNumber > self.totalPage) pageNumber = self.totalPage;
        //异步刷新页面模式
        if (p.asyncLoad) {
            self.pageNumber = pageNumber;
            var param = self.getParams(pageNumber);
            var async = true;
            if (p.async !== undefined && !p.async) async = p.async;
            if (!p.serverSidePage) {
                $.ajax({
                    url: p.url,
                    data: param,
                    async: async,
                    type: p.asyncType,
                    dataType: 'json',
                    success: function (returnData) {
                        self.pageNumber = returnData.pageNumber;
                        self.pageSize = returnData.pageSize;
                        self.totalRow = returnData.totalRow;
                        if (p.render && $.isFunction(p.render)) p.render(returnData);
                        if (p.callback && $.isFunction(p.callback)) p.callback(param);
                        self.populate();
                    }
                });
            }
        } else {
            //直接跳转模式
            window.location.href = self.setUrl(pageNumber);
        }
    };
    /**
     * 设置具体页码跳转的URL
     */
    pagination.prototype.setUrl = function (pNum) {
        var p = this.p, str = '';
        if (p.url) {
            var str = p.url + '?';
            str += 'p=' + pNum;
            //str += '&pageSize=' + this.pageSize;
            str += this.buildParamsStr(pNum);
        } else {
            str = 'javascript:void(0);';
        }
        return str;
    };

    /**
     * 插件初始化入口
     */
    function Plugin(p) {
        return this.each(function () {
            //参数合并时允许读取在html元素上定义的'data-'系列的参数
            var $this = $(this),
                data = $this.data('pagination'),
                params = $.extend({}, defaults, $this.data(), typeof p === 'object' && p);
            if (!data) $this.data('pagination', (data = new pagination(this, params)));
            if ($.isPlainObject(params)) data.init();
        });
    }

    /**
     * 切换当前页
     *
     * @param pNum {number} 目标分页
     */
    function paginationSwitch(pNum) {
        return this.each(function () {
            if (!pNum || $.type(pNum) !== 'number') return;
            var $this = $(this), data = $this.data('pagination');
            if (data) data.pageSwitch(pNum);
        });
    }

    /**
     * 刷新新页栏
     */
    function paginationRefresh(p) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('pagination'),
                params = $.extend({}, defaults, $this.data(), data && data.p, typeof p === 'object' && p);
            if ($.isPlainObject(params)) data.p = params;
            data.pageNumber = params.pageNumber;
            data.pageSize = params.pageSize;
            data.totalRow = params.totalRow;
            if (data) data.pageSwitch();
        });
    }

    var old = $.fn.pagination;

    $.fn.pagination = Plugin;
    $.fn.pagination.Constructor = pagination;
    $.fn.paginationSwitch = paginationSwitch;
    $.fn.paginationRefresh = paginationRefresh;

    // 处理新旧版本冲突
    $.fn.pagination.noConflict = function () {
        $.fn.pagination = old;
        return this;
    };

}(window.jQuery);
